/**
 * Copyright (C), 2018-2020, 龙腾出行
 * FileName: SessionContext
 * Author:   zhouw
 * Date:     2020/7/23 19:57
 * Description: 缓存信息存取
 * History:
 * <author>          <time>          <version>          <desc>
 * zhouw           19:57                       描述
 */
package cn.com.dragonpass.psystem.common.configuration;

import cn.com.dragonpass.common.base.AppException;
import cn.com.dragonpass.common.base.UserFriendlyException;
import cn.com.dragonpass.common.spring.callctx.CallContext;
import cn.com.dragonpass.common.utils.WebContextUtils;
import cn.com.dragonpass.platform.utils.RedisUserHashkey;
import cn.com.dragonpass.pmodel.common.enums.RedisKeyEnum;
import cn.com.dragonpass.pmodel.user.UserDto;
import cn.com.dragonpass.psystem.common.redis.JedisUtils;
import cn.com.dragonpass.psystem.common.util.JwtUtils;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.Locale;
import java.util.Map;

/**
 * 缓存信息存取
 *
 * @author zhouw
 * @create 2020/7/23
 * @since 1.0.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class SessionContext {

    private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);

    public final static String USER_ID_KEY = "_UID";

//    @Value("${disable-data-permission-control:false}")
    private boolean disableDataPermissionControl = true;

    /**
     * 当前Locale
     */
    @Getter
    private Locale locale;
    /**
     * 当前语言 ： zh-cn , en
     */
    @Getter
    private String language;


    @Autowired
    private MessageSource messageSource;
    /**
     * 获取多语言消息
     *
     * @param msgKey
     * @return
     */
    public String localize(String msgKey) {
        return localize(msgKey, msgKey);
    }

    /**
     * 获取多语言消息
     *
     * @param msgKey
     * @param defaultMsg
     * @return
     */

    public String localize(String msgKey, String defaultMsg) {
        return messageSource.getMessage(msgKey, null, defaultMsg, locale);
    }

    public void setLocale(Locale locale, String lg) {
        this.language=lg;
        this.locale=locale;
    }
    /**
     * 取缓存用户信息
     * */
    public UserDto.UserVo getUser() {
        String userId = getUid();
        String JsonString = JedisUtils.getInstance().get(RedisKeyEnum.UserId.keyBuilder() + userId);
        if (!StringUtils.isNotBlank(JsonString)) {
            throw new UserFriendlyException("login.fail");
        }
        UserDto.UserVo userVo = JSONObject.parseObject(JsonString, UserDto.UserVo.class);
        if (userVo == null) {
            throw new UserFriendlyException("login.fail");
        }
        return userVo;
    }



    protected String getUid() {
        Object unid = RequestContextHolder.getRequestAttributes().getAttribute(USER_ID_KEY, 0);
        if (null == unid) {
            unid = CallContext.getUserId();
        }
        if (null == unid) {
            logger.error("非法登陆");
            throw new UserFriendlyException("login.fail");
        }
        return (String) unid;
    }

    public String charistic() {
        if (disableDataPermissionControl) {
//            log.info("数据权限控制已禁用");
            return null;
        }

        return commonCharistic();
    }

    public String charisticEnablePermissionControl() {
        return commonCharistic();
    }

    private String commonCharistic() {
        String token = WebContextUtils.getInstance().getRequest().getHeader("Token");
        Claims claims = JwtUtils.getClaim(token);
        if (claims == null) {
            return null;
        }
        // 平台系统暂不做数据权限控制
        if ("platform-sys".equals(claims.get("sysCode"))) {
            return null;
        }

        String userID = CallContext.getUserId();
        Map<String, String> map = null;
        try {
            map = JedisUtils.getInstance().getMapNotKeyPrefix(String.format(RedisUserHashkey.KEY, userID));
        } catch (IllegalAccessError e) {
            log.info(e.getMessage(), e);
            AppException.throwEx("not.authority", "未获取到相应的数据权限，请确认相关配置", null, null);
        }
        log.info("获取Redis, 特征信息 : {}, {}", String.format(RedisUserHashkey.KEY, userID), map);
        if (!CollectionUtils.isEmpty(map)) {
            return map.get(RedisUserHashkey.COMPLEX_CHARISTIC_ROOT);
        }
        return null;
    }

    public String getUserName() {
        return getUser().getUserInfo().getUser();
    }

    public String getName() {
        return getUser().getUserInfo().getName();
    }

}